<template>
  <div class="good-operation">
    <el-collapse class="search-block" style="width: 1260px">
      <el-collapse-item title="条件搜索">
        <!-- 产品编号，产品名，开始到结束日期，添加区间 -->
        <el-form ref="searchGoodForm" :model="searchGoodForm" label-position="top">
          <el-form-item class="search-item" label="产品编号" prop="goodId">
            <el-input type="text" v-model="searchGoodForm.goodId" style="width: 200px" placeholder="请输入产品编号" />
          </el-form-item>
          <el-form-item class="search-item" label="产品名" prop="goodTitle">
            <el-input type="text" v-model="searchGoodForm.goodTitle" style="width: 200px" placeholder="请输入产品名"
              maxlength="10" />
          </el-form-item>

          <el-form-item class="search-item" label="产品价格区间">
            <el-form-item prop="firstPrices" class="search-item">
              <el-input type="text" v-model="searchGoodForm.firstPrices" style="width: 200px" placeholder="请输入产品初始价" />
            </el-form-item>
            至
            <el-form-item prop="secPrices" class="search-item" style="margin-left: 0px">
              <el-input type="text" v-model="searchGoodForm.secPrices" style="width: 200px" placeholder="请输入产品截至价" />
            </el-form-item>
          </el-form-item>

          <el-form-item label="是否开启秒杀" class="search-item" prop="isSeckill">
            <el-select v-model="searchGoodForm.isSeckill">
              <el-option label="否" value="0"></el-option>
              <el-option label="是" value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="是否需要快递" class="search-item" prop="isDelivery">
            <el-select v-model="searchGoodForm.isDelivery">
              <el-option label="否" value="0"></el-option>
              <el-option label="是" value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="秒杀时间" class="search-item" prop="seckillTime" v-if="searchGoodForm.isSeckill === '1'">
            <div class="block">
              <el-date-picker v-model="searchGoodForm.seckillTime" type="daterange" align="right" unlink-panels
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </div>
          </el-form-item>

          <el-form-item label="添加时间" class="search-item" prop="createTime">
            <div class="block">
              <el-date-picker v-model="searchGoodForm.createTime" type="daterange" align="right" unlink-panels
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </div>
          </el-form-item>

          <div class="search-button" style="margin-top: 100px">
            <el-button type="warning" icon="el-icon-search" @click="getGoodTableList()">搜 索</el-button>
            <el-button icon="el-icon-delete" @click="resetForm('searchGoodForm')">重 置</el-button>
          </div>
        </el-form>
      </el-collapse-item>
    </el-collapse>

    <div class="good-table">
      <el-table :data="goodTableList" stripe v-loading="goodTableLoading">
        <el-table-column prop="good_id" label="产品编号" align="center" width="100px" show-overflow-tooltip />
        <el-table-column prop="good_title" label="产品名" align="center" width="100px" show-overflow-tooltip />
        <el-table-column prop="price" label="产品价格/元" align="center" width="120px" show-overflow-tooltip />
        <el-table-column prop="seckill_price" label="秒杀价格" align="center" width="120px" show-overflow-tooltip />
        <el-table-column prop="total" label="总量" align="center" width="80px" show-overflow-tooltip />
        <el-table-column prop="remain" label="剩余数量" align="center" width="80px" show-overflow-tooltip />
        <el-table-column prop="is_seckill" label="是否秒杀" align="center" width="80px">
          <template slot-scope="scope">
            <span v-if="scope.row.is_seckill === '0'">否</span>
            <span v-else>是</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_delivery" label="是否快递" align="center" width="80px">
          <template slot-scope="scope">
            <span v-if="scope.row.is_delivery === '0'">否</span>
            <span v-else>是</span>
          </template>
        </el-table-column>
        <el-table-column prop="start_time" label="开始时间" align="center" width="100px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.start_time !== null">{{
              scope.row.start_time | dateFormat("yyyy-mm-dd hh:mm:ss")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" align="center" width="100px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.end_time !== null">{{
              scope.row.end_time | dateFormat("yyyy-mm-dd hh:mm:ss")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="添加时间" align="center" width="100px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.create_time !== null">{{
              scope.row.create_time | dateFormat("yyyy-mm-dd hh:mm:ss")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200px">
          <template slot-scope="scope">
            <el-button type="primary" @click="openEditGoodDialog(scope.row.good_id)">编辑</el-button>
            <el-button type="danger" @click="deleteGood(scope.row.good_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getGoodTableList" />
    </div>

    <div class="edit-good-dialog">
      <el-dialog title="编辑产品" width="464px" :visible.sync="editGoodDialog" :close-on-click-modal="false"
        :close-on-press-escape="false" center>
        <el-form ref="editGoodForm" :model="editGoodForm" :rules="editGoodRules" label-position="top">
          <!-- 产品图片、产品名、产品价格、产品秒杀价、产品总量、产品描述、开始时间、结束时间 -->
          <div class="upload-image">
            <el-form-item label="产品图片" prop="good_img">
              <el-image v-loading="uploadLoading" :src="editGoodForm.good_img">
              </el-image>
              <el-upload style="display: inline-block" :action="uploadUrl" list-type="picture"
                :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" :headers="headers"
                :on-error="handleUploadError" :show-file-list="false" name="file">
                <el-button type="primary">修改图片</el-button>
              </el-upload>
            </el-form-item>
          </div>

          <div class="edit-good-title">
            <el-form-item label="产品名" prop="good_title">
              <el-input type="text" maxlength="10" placeholder="请输入产品名" v-model="editGoodForm.good_title" />
            </el-form-item>
          </div>

          <div class="edit-good-desc">
            <el-form-item label="产品描述" prop="good_desc">
              <el-input type="textarea" maxlength="100" placeholder="请输入产品描述(小于100字)" v-model="editGoodForm.good_desc"
                show-word-limit />
            </el-form-item>
          </div>

          <div class="edit-good-is-seckill">
            <el-form-item label="是否开启秒杀" prop="is_seckill">
              <el-select v-model="editGoodForm.is_seckill">
                <el-option label="否" value="0"></el-option>
                <el-option label="是" value="1"></el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="edit-good-is-delivery">
            <el-form-item label="是否需要快递" prop="is_delivery">
              <el-select v-model="editGoodForm.is_delivery">
                <el-option label="否" value="0"></el-option>
                <el-option label="是" value="1"></el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="edit-good-prices">
            <el-form-item label="产品价格" prop="price">
              <el-input type="text" placeholder="请输入产品价格" v-model="editGoodForm.price" />
            </el-form-item>
          </div>

          <div class="edit-good-seckill-prices" v-if="editGoodForm.is_seckill === '1'">
            <el-form-item label="秒杀价格" prop="seckill_price">
              <el-input type="text" placeholder="请输入秒杀价格" v-model="editGoodForm.seckill_price" />
            </el-form-item>
          </div>

          <div class="edit-good-total">
            <el-form-item label="产品总量" prop="total">
              <el-input type="text" placeholder="请输入产品总量" v-model="editGoodForm.total" />
            </el-form-item>
          </div>

          <div class="edit-start-time" v-if="editGoodForm.is_seckill === '1'">
            <el-form-item label="开始时间" prop="start_time">
              <el-col :span="11">
                <el-date-picker type="date" placeholder="选择日期" v-model="editGoodForm.start_time"
                  style="width: 100%"></el-date-picker>
              </el-col>
              <el-col :span="11" style="margin-left: 5%">
                <el-time-picker placeholder="选择时间" v-model="editGoodForm.start_time" style="width: 100%"></el-time-picker>
              </el-col>
            </el-form-item>
          </div>

          <div class="edit-end-time" v-if="editGoodForm.is_seckill === '1'">
            <el-form-item label="结束时间" prop="end_time">
              <el-col :span="11">
                <el-date-picker type="date" placeholder="选择日期" v-model="editGoodForm.end_time"
                  style="width: 100%"></el-date-picker>
              </el-col>
              <el-col :span="11" style="margin-left: 5%">
                <el-time-picker placeholder="选择时间" v-model="editGoodForm.end_time" style="width: 100%"></el-time-picker>
              </el-col>
            </el-form-item>
          </div>

          <div class="edit-button">
            <el-button type="primary" :loading="editGoodLoading" @click="editGood()">
              <span v-if="!editGoodLoading">修 改</span>
              <span v-else>修 改 中...</span>
            </el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getGoodList, getGood, modifyGood, deleteGood } from "@/api/good";
import { getToken } from "@/utils/auth";
export default {
  name: "GoodOperation",
  data() {
    return {
      searchGoodForm: {
        goodId: "",
        goodTitle: "",
        firstPrices: "",
        secPrices: "",
        isSeckill: '',
        isDelivery: '',
        seckillTime: "",
        createTime: "",
      },

      queryParams: {
        pageNum: 1,
        pageSize: 5,
        goodId: "",
        goodTitle: "",
        firstPrices: "",
        secPrices: "",
        isSeckill: '',
        isDelivery: '',
        startDate: "",
        endDate: "",
        firstCreatTime: "",
        secCreateTime: "",
      },
      total: 0,

      goodTableList: [],
      goodTableLoading: false,
      editGoodDialog: false,
      editGoodLoading: false,

      editGoodForm: {
        good_img: "",
        good_title: "",
        good_desc: "",
        is_seckill: "",
        is_delivery: "",
        price: "",
        seckill_price: "",
        total: "",
        start_time: "",
        end_time: "",
      },
      editGoodRules: {
        good_img: [
          {
            required: true,
            message: "图片不能为空",
            trigger: "blur",
          },
        ],
        good_title: [
          {
            required: true,
            message: "产品名不能为空",
            trigger: "blur",
          },
        ],
        price: [
          {
            required: true,
            message: '产品价格不能为空',
            trigger: "blur",
          },
        ],
        seckill_price: [
          {
            required: true,
            message: '产品秒杀价不能为空',
            trigger: "blur",
          },
        ],
        total: [
          {
            required: true,
            message: '产品总量不能为空',
            trigger: "blur",
          },
        ],
        start_time: [
          {
            required: true,
            message: "请输入开始时间不能为空",
            trigger: "blur",
          },
        ],
        end_time: [
          {
            required: true,
            message: "请输入结束时间不能为空",
            trigger: "blur",
          },
        ],
      },
      uploadLoading: false,

      uploadUrl: "/api/file/upload",
      headers: {
        tokenAuthorization: "Bearer" + getToken(),
      },
    };
  },
  created() {
    this.getGoodTableList();
  },
  methods: {
    getGoodTableList() {
      this.packParams();
      this.goodTableLoading = true;
      getGoodList(this.queryParams)
        .then((res) => {
          this.goodTableList = res.rows;
          this.total = res.total;
          this.goodTableLoading = false;
        })
        .catch((err) => {
          this.goodTableLoading = false;
        });
    },
    packParams() {
      let form = this.searchGoodForm;
      if (form.goodId != null && form.goodId != "") {
        if (isNaN(form.goodId)) {
          this.$message.error("产品编号是数字");
          return;
        }
      }
      if (form.firstPrices != null && form.firstPrices != "") {
        if (isNaN(form.firstPrices)) {
          this.$message.error("价格是数字");
          return;
        }
      }
      if (form.secPrices != null && form.secPrices != "") {
        if (isNaN(form.secPrices)) {
          this.$message.error("价格是数字");
          return;
        }
      }
      this.queryParams.goodId = form.goodId;
      this.queryParams.goodTitle = form.goodTitle;
      this.queryParams.firstPrices = form.firstPrices;
      this.queryParams.secPrices = form.secPrices;
      this.queryParams.isSeckill = form.isSeckill;
      this.queryParams.isDelivery = form.isDelivery;
      this.queryParams.startDate =
        form.seckillTime === null ? null : form.seckillTime[0];
      this.queryParams.endDate =
        form.seckillTime === null ? null : form.seckillTime[1];
      this.queryParams.firstCreatTime =
        form.createTime === null ? null : form.createTime[0];
      this.queryParams.secCreateTime =
        form.createTime === null ? null : form.createTime[1];

      if (this.queryParams.isSeckill === '0') {
        this.queryParams.startDate = null
        this.queryParams.endDate = null
      }
    },
    openEditGoodDialog(goodId) {
      getGood(goodId).then((res) => {
        this.editGoodForm = res.data;
        if (this.editGoodForm.is_seckill === '1' && new Date(this.editGoodForm.start_time) - new Date() <= 86400000) {
          this.$confirm("该产品在秒杀前一天或秒杀已结束，无法修改", "注意", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "error",
          })
            .then(() => {
              this.editGoodForm = null;
              this.editGoodDialog = false;
              return false;
            })
            .catch(() => { });
        } else this.editGoodDialog = true;
      });
    },
    editGood() {
      if (this.editGoodForm.is_seckill === '0') {
        this.editGoodForm.seckill_price = ''
        this.editGoodForm.start_time = ''
        this.editGoodForm.end_time = ''
      }

      this.$refs.editGoodForm.validate((valid) => {
        if (valid) {
          if (this.editGoodForm.is_seckill === '1' && isNaN(this.editGoodForm.seckill_price)) {
            this.$message.error('产品秒杀价只能是数字')
            return false
          }

          if (this.editGoodForm.is_seckill === '1') {

            let startDate = new Date(this.editGoodForm.start_time)
            let endDate = new Date(this.editGoodForm.end_time)

            if (startDate >= endDate) {
              this.$message.error('开始时间必须在结束日期前')
              return false
            }
          }

          if (isNaN(this.editGoodForm.price)) {
            this.$message.error('产品价格只能是数字')
            return false
          }

          if (isNaN(this.editGoodForm.total)) {
            this.$message.error('产品总量只能是数字')
            return false
          }

          this.editGoodLoading = true;

          modifyGood(this.editGoodForm)
            .then(() => {
              this.$message.success("修改成功!");
              this.editGoodLoading = false;
              this.editGoodDialog = false;
              this.getGoodTableList();
            })
            .catch(() => {
              this.editGoodLoading = false;
            });
        } else {
          return false
        }

      })
    },
    deleteGood(goodId) {
      this.$confirm("确定要删除该产品吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteGood(goodId).then((res) => {
            this.$message.success("删除成功");
            this.getGoodTableList();
          });
        })
        .catch(() => { });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.getGoodTableList();
    },
    handleUploadSuccess(res) {
      this.$message.success("上传成功！");
      this.editGoodForm.good_img = res.data.url;
      this.uploadLoading = false;
    },

    handleBeforeUpload(file) {
      let fileExtension = "";
      if (file.name.lastIndexOf(".") > -1) {
        fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
      }

      if (
        fileExtension != "jpg" &&
        fileExtension != "png" &&
        fileExtension != "jpeg"
      ) {
        this.$message.error("上传图片格式不符");
        return false;
      }

      const fileSize = file.size / 1024 / 1024 < 5;
      if (!fileSize) {
        this.$message.error("上传图片大小不能超过 5MB!");
        return false;
      }

      this.uploadLoading = true;
    },

    handleUploadError() {
      this.$message.error("上传失败，请稍后重试");
      this.uploadLoading = false;
    },
  },
};
</script>

<style>
.search-block {
  margin-bottom: 20px;
}

.el-collapse-item__header {
  color: #4091ff !important;
  font-size: 15px;
}

.search-item {
  display: inline-block;
  margin-left: 20px;
}

.el-form-item__label {
  padding-bottom: 0px !important;
}

.search-button {
  float: right;
  margin-bottom: 20px;
}

.image-uploade .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-left: 30px;
  margin-top: 10px;
}

.image-uploade .el-upload:hover {
  border-color: #409eff;
}

.image-uploade-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.image {
  width: 200px;
  height: 100px;
  display: block;
}

.el-form-item__label {
  padding-bottom: 0px !important;
}

.edit-button {
  display: flex;
  justify-content: center;
}

.edit-button .el-button {
  width: 200px;
  height: 40px;
}
</style>